package com.fowo.api.service.handleWork;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.controller.purchase.importPo.StockOutProductImportPo;
import com.fowo.api.controller.purchase.vo.WarehouseBinParam;
import com.fowo.api.controller.purchase.vo.WarehouseBinStockVo;
import com.fowo.api.entity.Product;
import com.fowo.api.model.stock.out.product.StockOutProductItemVo;
import com.fowo.api.service.ListingFatherService;
import com.fowo.api.service.ShopInfoService;
import com.fowo.api.service.impl.ProductServiceImpl;
import com.fowo.api.service.impl.WarehouseBinDServiceImpl;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysImportTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
@DS("ds24")
public class StockOutDServiceImpl {
    @Resource
    protected SysImportTemplateService importTemplateService;
    @Resource
    protected FileService fileService;
    @Resource
    protected Validator validator;
    @Resource
    private ProductServiceImpl productService;
    @Resource
    private ShopInfoService shopInfoService;
    @Resource
    private ListingFatherService listingFatherService;
    @Resource
    private WarehouseBinDServiceImpl warehouseBinDService;


    public List<StockOutProductItemVo> importPreview(
            SysFile sysFile,
            Long templateId,
            boolean allowOverrides,
            Long wid
    ) throws Exception {
        SysImportTemplate importTemplate = null;
        if (templateId != null && templateId > 0) {
            importTemplate = importTemplateService.getById(templateId);
            if (importTemplate == null) {
                throw new RException("指定的模版不可用！");
            }
        }
        Map<String, Object> variables = new HashMap<>();
        try (InputStream in = fileService.read(sysFile)) {
            List<ImportRow<StockOutProductImportPo>> rows = new ArrayList<>();
            List<StockOutProductItemVo> voList = new ArrayList<>();

            // 读取 Excel 到 rows
            EasyExcel
                    .read(in)
                    .useDefaultListener(false)
                    .registerReadListener(
                            new TemplateModelBuildEventListener<>(
                                    StockOutProductImportPo.class,
                                    importTemplate
                            ) {
                                @Override
                                public void invokeRow(
                                        StockOutProductImportPo row,
                                        AnalysisContext cxt
                                ) {
                                    StockOutProductItemVo vo = new StockOutProductItemVo();
                                    ImportRow<StockOutProductImportPo> ir = excelToImportRow(
                                            row,
                                            cxt.readRowHolder().getRowIndex(),
                                            vo,
                                            variables,
                                            allowOverrides,
                                            wid
                                    );
                                    if (ir.isEmptyRow()) {
                                        return;
                                    }
                                    if (allowOverrides) {
                                        // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
                                    }
                                    rows.add(ir);
                                    voList.add(vo);
                                }
                            }
                    )
                    .sheet()
                    .doRead();
            return voList;
        }
    }

    protected ImportRow<StockOutProductImportPo> excelToImportRow(
            StockOutProductImportPo row,
            Integer rowNumber,
            StockOutProductItemVo vo,
            Map<String, Object> variables,
            boolean allowOverrides,
            Long wid
    ) {
        ImportRow<StockOutProductImportPo> ir = new ImportRow<StockOutProductImportPo>();
        ir.setRowNumber(rowNumber);
        ir.setRow(row);
        if (SheetUtils.isAllFieldsEmpty(row)) {
            ir.setEmptyRow(true);
            ir.addError("", "空行");
            return ir;
        }
        final Set<ConstraintViolation<StockOutProductImportPo>> validate = validator.validate(
                row
        );
        boolean isOutputVo = vo != null;
        if (!isOutputVo) {
            vo = new StockOutProductItemVo();
        }
        BeanUtils.copyProperties(row, vo);
        // 收集基本校验错误
        ir.initErrors(validate, StockOutProductImportPo.class);

        if(StringUtils.hasText(row.getProductGoodNum())) {
            vo.setProductGoodNum(new BigDecimal(row.getProductGoodNum()).intValue());
        }
        if(StringUtils.hasText(row.getProductBadNum())){
            vo.setProductBadNum(new BigDecimal(row.getProductBadNum()).intValue());
        }
        if (StringUtils.hasText(row.getSku())) {
            final Product product = productService.getOne(Wrappers.lambdaQuery(Product.class).eq(Product::getSku, row.getSku()));
            if (product == null) {
                ir.addError("SKU", row.getSku() + "产品不存在");
            }else {
                vo.setProductImg(product.getPicUrl());
                vo.setProductId(product.getId());
            }
        }
        if(StringUtils.hasText(row.getSidShopName())){
            final Long shopId = shopInfoService.getIdByShopName(row.getSidShopName());
            if(null == shopId){
                ir.addError("店铺", row.getSidShopName() + "不存在");
            }else {
                vo.setSid(shopId);

            }
        }
        if(StringUtils.hasText(row.getFnskuIdFnsku())){
            final Long fnsku = listingFatherService.getIdByFnsku(row.getFnskuIdFnsku());
            if(null == fnsku){
                ir.addError("FNSKU", row.getFnskuIdFnsku() + "不存在");
            }else {
                vo.setFnskuId(fnsku);
                vo.setFnsku(row.getFnskuIdFnsku());
            }
        }

        try{
            WarehouseBinParam search = new WarehouseBinParam();
            search.setWarehouseId(wid);
            search.setSku(row.getSku());
            search.setType(5L);
            search.setShopId(vo.getSid());
            search.setFnskuName(vo.getFnsku());
            final List<WarehouseBinStockVo> binByWarehouse = warehouseBinDService.getBinByWarehouse(search);
            if(CollectionUtil.isNotEmpty(binByWarehouse)){
                vo.setStorageBinGoodId(binByWarehouse.get(0).getId());
                vo.setStorageBinGoodIdStorageBin(binByWarehouse.get(0).getStorageBin());
                vo.setGoodNum(binByWarehouse.get(0).getStockQty().longValue());
            }
        }catch (Exception e){

        }

        return ir;
    }
}

